package com.beans;

import java.util.Arrays;

public class UDPProtocal {

    private final int EXPAND_SIZE = 15;
    private byte[] buffer = new byte[0];
    private int tail = 0;

    public UDPProtocal(int cmd) {
        expand();

        //固定头，4字节
        pushByte((byte) 0x55);
        pushByte((byte) 0xAA);

        //长度
        pushByte((byte) 0);//updateLen()方法会填充的
        pushByte((byte) 0);

        //命令号
        pushByte((byte) cmd);

    }

    /**
     * 获取构建后的数据
     *
     * @return
     */
    public byte[] getData() {
        completeCompose();
        return buffer;
    }

    /**
     * 完成构建
     */
    private void completeCompose() {
        pushByte((byte) 0x00);//校验位
        pushByte((byte) 0x00);
        byte valueByte = 0;
        for (int i = 0; i < tail; i++) {
            valueByte += buffer[i];
        }
        buffer = Arrays.copyOf(buffer, tail);
        buffer[buffer.length - 2] = valueByte;
    }

    /**
     *
     */
    private void expand() {
        int newLen = buffer.length + EXPAND_SIZE;
        buffer = Arrays.copyOf(buffer, newLen);
    }

    /**
     * 添加一个字节
     *
     * @param value
     */
    public void pushByte(Byte value) {
        if (tail == buffer.length) {
            expand();
        }
        buffer[tail++] = value;
        updateLen();
    }

    /**
     * 更新总长
     */
    private void updateLen() {
        buffer[2] = (byte) (tail >> 8);
        buffer[3] = (byte) (tail & 0xFF);
    }
}
